// 全局变量定义
window.questionnaireInfo = {
    questions: [], // 存储题目信息，包括类型、选项等信息
    initialized: false // 标记是否已初始化
};



// 获取问卷配置
function getQuestionConfigs() {
    const configs = [];
    document.querySelectorAll('.question-item').forEach((questionItem, index) => {
        const typeText = questionItem.querySelector('.question-type').textContent.trim();
        let type;
        switch(typeText) {
            case '[单选题]': type = 'SINGLE_CHOICE'; break;
            case '[多选题]': type = 'MULTIPLE_CHOICE'; break;
            case '[文本题]': type = 'TEXT'; break;
            default: throw new Error(`不支持的问题类型：${typeText}`);
        }

        const questionConfig = {
            questionId: index,
            type: type,
            options: [],
            hasTextInput: false  // 添加标记，表示问题是否包含需要文本输入的选项
        };

        // 处理选项配置
        if (type === 'SINGLE_CHOICE' || type === 'MULTIPLE_CHOICE') {
            questionItem.querySelectorAll('.option-row').forEach((optionRow, optionIndex) => {
                const percentage = parseInt(optionRow.querySelector('.percentage-slider').value) || 0;
                const textAnswersList = optionRow.querySelector('.text-answers-list');
                const hasTextInput = !!textAnswersList; // 检查该选项是否需要文本输入

                if (hasTextInput) {
                    questionConfig.hasTextInput = true; // 标记问题包含需要文本输入的选项
                }

                const option = {
                    optionNumber: optionIndex,
                    percentage: percentage,
                    hasTextInput: hasTextInput,
                    textAnswers: []
                };

                // 如果选项需要文本输入，收集文本答案
                if (hasTextInput) {
                    textAnswersList.querySelectorAll('.text-answer').forEach(textarea => {
                        const answer = textarea.value.trim();
                        if (answer) {
                            option.textAnswers.push(answer);
                        }
                    });
                    // 如果没有输入任何答案，添加默认答案
                    if (option.textAnswers.length === 0) {
                        option.textAnswers.push("其他内容");
                    }
                }

                questionConfig.options.push(option);
            });
        } else if (type === 'TEXT') {
            // 处理文本题答案
            const textAnswers = [];
            questionItem.querySelectorAll('.text-answer').forEach(textarea => {
                const answer = textarea.value.trim();
                if (answer) {
                    textAnswers.push(answer);
                }
            });
            questionConfig.textAnswers = textAnswers.length > 0 ? textAnswers : ["无"];
        }

        configs.push(questionConfig);
    });
    return configs;
}

// 生成指定范围内的随机数
function getRandomInterval(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


// 提交任务
async function submitTask(e) {
    e.preventDefault();

    try {
        const url = document.getElementById('url').value.trim();
        if (!url) {
            alert('请输入问卷URL');
            return;
        }

        const count = parseInt(document.getElementById('fillCount').value);
        if (isNaN(count) || count < 1) {
            alert('请输入有效的填写次数（至少为1）');
            return;
        }

        const intervalMin = parseInt(document.getElementById('intervalMin').value);
        const intervalMax = parseInt(document.getElementById('intervalMax').value);
        if (isNaN(intervalMin) || isNaN(intervalMax) || intervalMin < 0 || intervalMax < intervalMin) {
            alert('请输入有效的时间间隔');
            return;
        }

        // 在区间内生成随机间隔时间
        const interval = getRandomInterval(intervalMin, intervalMax);

        const request = {
            url: url,
            count: count,
            waitTime: interval,
            useProxy: document.getElementById('useProxy').checked,
            proxyId: document.getElementById('proxySelect').value,
            title: document.querySelector('.questionnaire-title')?.textContent || '未命名问卷',
            questionConfigs: getQuestionConfigs()
        };

        // 显示任务状态
        const taskStatus = document.getElementById('taskStatus');
        if (taskStatus) {
            taskStatus.style.display = 'block';
        }


        const response = await fetch('/api/fill', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': localStorage.getItem('token')
            },
            body: JSON.stringify(request)
        });
        const result = await response.json();
        if (result.status === 200) {
            alert('创建任务成功');
        }
        else {
            alert('创建任务失败：' + result.msg);
        }


        // 保存URL到历史记录
        saveUrlToHistory(url);

    } catch (error) {
        console.error('创建任务失败：', error);
        // 使用原生alert替代SweetAlert2
        alert('创建任务时发生错误：' + error.message);

        // 隐藏任务状态
        const taskStatus = document.getElementById('taskStatus');
        if (taskStatus) {
            taskStatus.style.display = 'none';
        }
    }
}

// 添加表单提交事件监听
document.getElementById('questionnaireForm').addEventListener('submit', submitTask);

// 代理选择切换
document.getElementById('useProxy').addEventListener('change', function() {
    document.getElementById('proxySelect').disabled = !this.checked;
});

// 问卷解析
document.getElementById('parseBtn').addEventListener('click', async function() {
    const url = document.getElementById('url').value.trim();
    if (!url) {
        alert('请输入问卷链接');
        return;
    }


    // 显示解析状态
    document.querySelector('.parse-status').style.display = 'flex';

    try {
        // 调用后端解析接口
        console.log('开始解析问卷：' + url);
        const response = await fetch('/api/parse', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ url }),
        });

        if (!response.ok) {
            throw new Error('解析失败');
        }
        console.log('解析成功：', response);

        const data = await response.json();
        console.log(data);

        // 显示问卷内容
        document.getElementById('questionnaireContent').style.display = 'block';
        document.getElementById('taskConfig').style.display = 'block';

        // 更新问卷信息
        document.querySelector('.questionnaire-title').textContent = data.title;
        document.querySelector('.questionnaire-desc').textContent = data.description;

        // 在解析成功后再保存到历史记录
        saveUrlToHistory(url);

        // 渲染题目列表
        renderQuestions(data.data.questions);


    } catch (error) {
        alert('问卷解析失败：' + error.message);
    } finally {
        document.querySelector('.parse-status').style.display = 'none';
    }
});

// 答题模式切换
document.addEventListener('change', function(e) {
    if (e.target.name && e.target.name.startsWith('answerMode_')) {
        const select = e.target.closest('.option-item').querySelector('.answer-select');
        select.disabled = e.target.value === 'random';
    }
});

// 渲染选项
function renderOptions(question, index, contentDiv) {
    console.log('渲染选项，问题索引:', index);

    if (!Array.isArray(question.options)) {
        console.error('选项不是数组类型:', question.options);
        return;
    }

    const isSingleChoice = question.type === 'SINGLE_CHOICE';
    const defaultValue = Math.round(isSingleChoice ? (100 / question.options.length) : 50);

    // 创建一个容器来存放反向计分和分值设置
    const scoreSettingsContainer = document.createElement('div');
    scoreSettingsContainer.className = 'score-settings-container';
    scoreSettingsContainer.style.display = 'none'; // 默认隐藏
    
    if (isSingleChoice) {
        // 添加反向计分选项
        const reverseScoreCheckbox = document.createElement('div');
        reverseScoreCheckbox.className = 'reverse-score-option';
        reverseScoreCheckbox.innerHTML = `
            <label>
                <input type="checkbox" class="reverse-score-checkbox" data-question-index="${index}">
                反向计分
            </label>
            <span class="tooltip-text">选中后将反转选项分值（如5分变为1分）</span>
        `;
        scoreSettingsContainer.appendChild(reverseScoreCheckbox);
        contentDiv.appendChild(scoreSettingsContainer);
    }

    question.options.forEach((option, optionIndex) => {
        const optionRow = document.createElement('div');
        optionRow.className = 'option-row';

        const optionText = option.optionText || '未知选项';
        const defaultScore = optionIndex + 1;  // 默认1-based赋分

        // 如果选项需要文本输入，添加文本答案配置区域
        const hasTextInput = option.hasTextInput;
        const textInputHtml = hasTextInput ? `
            <div class="text-input-config">
                <div class="text-answers-header">
                    此选项的文本答案（系统将随机选择其中之一）
                </div>
                <div class="text-answers-list" data-option-index="${optionIndex}">
                    <div class="text-answer-item">
                        <textarea class="text-answer" 
                                placeholder="请输入一个可能的回答，不输入则默认回答无"
                                rows="2"></textarea>
                        <button class="btn btn-small btn-error remove-answer" style="display: none;">删除</button>
                    </div>
                </div>
                <button class="btn btn-small add-answer">+ 添加另一个可能的回答</button>
            </div>
        ` : '';

        // 创建分值设置的HTML
        const scoreInputHtml = isSingleChoice ? `
            <div class="option-score" style="display: none;">
                <label>分值：</label>
                <input type="number" class="score-input" 
                       value="${defaultScore}" 
                       min="-10" 
                       max="10" 
                       data-question-index="${index}"
                       data-option-index="${optionIndex}">
            </div>
        ` : '';

        optionRow.innerHTML = `
            <div class="option-main">
                <div class="option-text">
                    ${optionText}
                    ${hasTextInput ? '<span class="text-input-badge">需要填写文本</span>' : ''}
                    ${scoreInputHtml}
                    <span class="percentage-value">${defaultValue}%</span>
                </div>
                <div class="slider-container">
                    <input type="range" class="percentage-slider"
                           min="0" max="100" step="1"
                           value="${defaultValue}"
                           data-question-index="${index}"
                           data-option-index="${optionIndex}">
                    <div class="progress-container">
                        <div class="progress-bar" style="width: ${defaultValue}%"></div>
                        <div class="progress-label">${defaultValue}%</div>
                    </div>
                </div>
            </div>
            ${textInputHtml}
        `;
        contentDiv.appendChild(optionRow);

        // 如果选项包含文本输入，绑定添加/删除答案的事件处理
        if (hasTextInput) {
            const textInputConfig = optionRow.querySelector('.text-input-config');
            if (textInputConfig) {
                bindTextAnswerEvents(textInputConfig);
            }
        }
    });

    // 只有单选题才添加反向计分事件监听
    if (isSingleChoice) {
        const reverseCheckbox = contentDiv.querySelector('.reverse-score-checkbox');
        if (reverseCheckbox) {
            reverseCheckbox.addEventListener('change', function() {
                const scoreInputs = contentDiv.querySelectorAll('.score-input');
                const maxScore = scoreInputs.length;
                
                scoreInputs.forEach((input, index) => {
                    const currentValue = parseInt(input.value);
                    if (this.checked) {
                        // 反向计分：将分值反转
                        input.value = maxScore - currentValue + 1;
                    } else {
                        // 恢复正向计分
                        input.value = index + 1;
                    }
                });
            });
        }
    }

    const totalDiv = document.createElement('div');
    totalDiv.className = 'percentage-total';
    const initialTotal = isSingleChoice ? 100 : (50 * question.options.length);
    totalDiv.textContent = `总计：${Math.round(initialTotal)}%`;
    totalDiv.style.color = isSingleChoice ? (Math.abs(initialTotal - 100) < 1 ? '#495057' : '#dc3545') : '#495057';
    contentDiv.appendChild(totalDiv);

    // 监听百分比输入变化
    const sliders = contentDiv.querySelectorAll('.percentage-slider');
    let isAdjusting = false;

    const updateAllValues = () => {
        const slidersList = Array.from(sliders);
        const total = Math.round(slidersList.reduce((sum, s) => sum + parseFloat(s.value), 0));

        slidersList.forEach(slider => {
            const value = Math.round(parseFloat(slider.value));
            const container = slider.nextElementSibling;
            const bar = container.querySelector('.progress-bar');
            const label = container.querySelector('.progress-label');
            const valueDisplay = slider.closest('.option-row').querySelector('.percentage-value');

            bar.style.width = `${value}%`;
            label.textContent = `${value}%`;
            valueDisplay.textContent = `${value}%`;
        });

        totalDiv.textContent = `总计：${total}%`;
        if (isSingleChoice) {
            totalDiv.style.color = Math.abs(total - 100) < 1 ? '#495057' : '#dc3545';
        }
    };

    sliders.forEach(slider => {
        slider.addEventListener('input', function() {
            if (isAdjusting) return;
            isAdjusting = true;

            try {
                const currentValue = Math.round(parseFloat(this.value));
                const slidersList = Array.from(sliders);

                if (isSingleChoice) {
                    const otherSliders = slidersList.filter(s => s !== this);
                    const otherSum = Math.round(otherSliders.reduce((sum, s) => sum + parseFloat(s.value), 0));

                    if (currentValue + otherSum !== 100) {
                        const remaining = Math.max(0, 100 - currentValue);
                        const oldOtherSum = otherSum;

                        if (oldOtherSum > 0) {
                            // 按比例分配剩余值，确保结果为整数
                            let remainingToDistribute = remaining;
                            otherSliders.forEach((s, i) => {
                                if (i === otherSliders.length - 1) {
                                    // 最后一个选项获取所有剩余值，确保总和为100
                                    s.value = remainingToDistribute;
                                } else {
                                    const ratio = parseFloat(s.value) / oldOtherSum;
                                    const newValue = Math.round(ratio * remaining);
                                    s.value = newValue;
                                    remainingToDistribute -= newValue;
                                }
                            });
                        } else {
                            // 平均分配剩余值，处理可能的舍入问题
                            const equalShare = Math.floor(remaining / otherSliders.length);
                            const remainder = remaining - (equalShare * otherSliders.length);

                            otherSliders.forEach((s, i) => {
                                s.value = equalShare + (i < remainder ? 1 : 0);
                            });
                        }
                    }
                }

                updateAllValues();

            } finally {
                isAdjusting = false;
            }
        });
    });
}

// 添加文本答案相关事件处理函数
function bindTextAnswerEvents(container) {
    const answersList = container.querySelector('.text-answers-list');
    const addButton = container.querySelector('.add-answer');

    // 添加新答案
    addButton.addEventListener('click', () => {
        const newAnswerItem = document.createElement('div');
        newAnswerItem.className = 'text-answer-item';
        newAnswerItem.innerHTML = `
            <textarea class="form-input text-answer" 
                      placeholder="请输入一个可能的回答，不输入则默认回答无"
                      rows="2"></textarea>
            <button class="btn btn-small btn-error remove-answer">删除</button>
        `;
        answersList.appendChild(newAnswerItem);

        // 显示所有删除按钮
        answersList.querySelectorAll('.remove-answer').forEach(btn => {
            btn.style.display = 'block';
        });
    });

    // 删除答案
    container.addEventListener('click', (e) => {
        if (e.target.classList.contains('remove-answer')) {
            const answerItems = answersList.querySelectorAll('.text-answer-item');
            if (answerItems.length > 1) {
                e.target.closest('.text-answer-item').remove();

                // 如果只剩一个答案，隐藏其删除按钮
                if (answersList.querySelectorAll('.text-answer-item').length === 1) {
                    answersList.querySelector('.remove-answer').style.display = 'none';
                }
            }
        }
    });
}

// 渲染文本题
function renderTextQuestion(question, contentDiv, index) {
    const textAnswersDiv = document.createElement('div');
    textAnswersDiv.className = 'text-answers';

    // 添加标题
    const headerDiv = document.createElement('div');
    headerDiv.className = 'text-answers-header';
    headerDiv.textContent = '默认答案列表（系统将随机选择其中之一作答，不输入则默认回答"无"）';
    textAnswersDiv.appendChild(headerDiv);

    // 文本答案列表
    const answersListDiv = document.createElement('div');
    answersListDiv.className = 'text-answers-list';
    answersListDiv.setAttribute('data-question-index', index);

    // 添加默认的第一个答案框
    const defaultAnswerDiv = document.createElement('div');
    defaultAnswerDiv.className = 'text-answer-item';
    defaultAnswerDiv.innerHTML = `
        <textarea class="form-input text-answer"
                  placeholder="请输入一个可能的回答，不输入则默认回答无"
                  rows="2"></textarea>
        <button class="btn btn-small btn-error remove-answer" style="display: none;">删除</button>
    `;
    answersListDiv.appendChild(defaultAnswerDiv);

    // 添加按钮
    const addButton = document.createElement('button');
    addButton.className = 'btn btn-small add-answer';
    addButton.textContent = '+ 添加另一个可能的回答';

    textAnswersDiv.appendChild(answersListDiv);
    textAnswersDiv.appendChild(addButton);
    contentDiv.appendChild(textAnswersDiv);

    // 绑定添加答案事件
    addButton.addEventListener('click', function() {
        const newAnswerDiv = document.createElement('div');
        newAnswerDiv.className = 'text-answer-item';
        newAnswerDiv.innerHTML = `
            <textarea class="form-input text-answer"
                      placeholder="请输入一个可能的回答，不输入则默认回答无"
                      rows="2"></textarea>
            <button class="btn btn-small btn-error remove-answer">删除</button>
        `;
        answersListDiv.appendChild(newAnswerDiv);

        // 显示所有删除按钮
        answersListDiv.querySelectorAll('.remove-answer').forEach(btn => {
            btn.style.display = 'block';
        });
    });

    // 绑定删除答案事件
    textAnswersDiv.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-answer')) {
            const answerItems = answersListDiv.querySelectorAll('.text-answer-item');
            if (answerItems.length > 1) {
                e.target.closest('.text-answer-item').remove();

                // 如果只剩一个答案，隐藏其删除按钮
                if (answersListDiv.querySelectorAll('.text-answer-item').length === 1) {
                    answersListDiv.querySelector('.remove-answer').style.display = 'none';
                }
            }
        }
    });
}

// 渲染问题
function renderQuestions(questions) {
    console.log('开始渲染问题列表:', questions);

    const container = document.getElementById('questions-container');
    if (!container) {
        console.error('找不到问题容器元素 #questions-container');
        throw new Error('找不到问题容器元素');
    }

    try {
        container.innerHTML = '';
        container.style.display = 'block'; // 显示容器

        // 显示整个问卷内容卡片
        const questionnaireContent = document.getElementById('questionnaireContent');
        if (questionnaireContent) {
            questionnaireContent.style.display = 'block';
        }

        // 初始化题型信息
        window.questionnaireInfo.questions = [];
        window.questionnaireInfo.initialized = true;

        questions.forEach((question, index) => {
            console.log(`渲染第${index + 1}个问题:`, question);

            // 存储题型信息
            window.questionnaireInfo.questions.push({
                type: question.type,
                isSingleChoice: question.type === 'SINGLE_CHOICE',
                optionsCount: question.options ? question.options.length : 0
            });

            const questionDiv = document.createElement('div');
            questionDiv.className = 'question-item';

            // 添加问题标题和类型
            const headerDiv = document.createElement('div');
            headerDiv.className = 'question-header';
            const questionType = question.type === 'SINGLE_CHOICE' ? '单选题' :
                               question.type === 'MULTIPLE_CHOICE' ? '多选题' : '文本题';
            headerDiv.innerHTML = `
                <span class="question-number">${index + 1}. </span>
                <span class="question-title">${question.title || ''}</span>
                <span class="question-type">[${questionType}]</span>
            `;
            questionDiv.appendChild(headerDiv);

            const contentDiv = document.createElement('div');
            contentDiv.className = 'question-content';

            if (question.type === 'SINGLE_CHOICE' || question.type === 'MULTIPLE_CHOICE') {
                renderOptions(question, index, contentDiv);
            } else if (question.type === 'TEXT') {
                renderTextQuestion(question, contentDiv, index);
            }

            questionDiv.appendChild(contentDiv);
            container.appendChild(questionDiv);
        });

        console.log('题型信息初始化完成:', window.questionnaireInfo);
    } catch (error) {
        console.error('渲染问题时出错:', error);
        throw error;
    }
}


// 保存URL到历史记录
function saveUrlToHistory(url) {
    let urlHistory = JSON.parse(localStorage.getItem('urlHistory') || '[]');
    const now = new Date().toISOString();

    // 获取当前问卷标题
    const questionnaireTitle = document.querySelector('.questionnaire-title')?.textContent || '未命名问卷';

    // 如果已存在则更新时间
    const existingIndex = urlHistory.findIndex(item => item.url === url);
    if (existingIndex !== -1) {
        urlHistory.splice(existingIndex, 1);
    }

    // 添加到开头
    urlHistory.unshift({
        url: url,
        time: now,
        title: questionnaireTitle || '未命名问卷'
    });

    // 最多保存10条记录
    if (urlHistory.length > 10) {
        urlHistory.pop();
    }

    localStorage.setItem('urlHistory', JSON.stringify(urlHistory));
    updateUrlHistoryList();
}

// 更新URL历史记录列表
function updateUrlHistoryList() {
    const urlHistory = JSON.parse(localStorage.getItem('urlHistory') || '[]');
    const historyList = document.getElementById('historyList');

    if (urlHistory.length === 0) {
        historyList.innerHTML = '<div class="empty-history">暂无解析记录</div>';
        return;
    }

    historyList.innerHTML = urlHistory.map(item => `
        <div class="history-item" onclick="useHistoryUrl('${item.url}')" title="点击直接解析该问卷">
            <div class="history-item-icon">
                <i class="fas fa-file-alt"></i>
            </div>
            <div class="history-item-content">
                <div class="history-item-title">${item.title}</div>
                <div class="history-item-url">${item.url}</div>
            </div>
            <div class="history-item-time">
                ${formatTime(new Date(item.time))}
            </div>
        </div>
    `).join('');
}

// 使用历史记录中的URL
function useHistoryUrl(url) {
    document.getElementById('url').value = url;
}

// 清空历史记录
function clearUrlHistory() {
    if (confirm('确定要清空所有历史记录吗？')) {
        localStorage.removeItem('urlHistory');
        updateUrlHistoryList();
    }
}

// 格式化时间
function formatTime(date) {
    const now = new Date();
    const diff = now - date;

    // 小于1分钟
    if (diff < 60000) {
        return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于24小时
    if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前';
    }
    // 大于24小时
    return date.toLocaleDateString();
}

// 页面加载时初始化历史记录
document.addEventListener('DOMContentLoaded', () => {
    updateUrlHistoryList();
});


document.addEventListener('DOMContentLoaded', async function() {


    // 添加清空按钮事件处理
    document.getElementById('clearBtn').addEventListener('click', function() {
        document.getElementById('url').value = '';
    });


    // 显示用户名
    const username = localStorage.getItem('username');
    if (username) {
        document.querySelector('.nav-logo').textContent = `问卷自动化系统 `;
    }

    // 初始化URL历史记录列表
    updateUrlHistoryList();

    document.querySelectorAll('.progress-container').forEach(container => {
        container.addEventListener('mouseover', () => {
            container.style.transform = 'scale(1.02)';
        });
        container.addEventListener('mouseout', () => {
            container.style.transform = 'scale(1)';
        });
    });

    // 监听信效度检验的启用状态
    const enableReliabilityCheckbox = document.getElementById('enableReliability');
    if (enableReliabilityCheckbox) {
        enableReliabilityCheckbox.addEventListener('change', function() {
            // 显示或隐藏所有单选题的分值设置
            document.querySelectorAll('.question-item').forEach(questionItem => {
                const typeText = questionItem.querySelector('.question-type').textContent.trim();
                if (typeText === '[单选题]') {
                    const scoreSettingsContainer = questionItem.querySelector('.score-settings-container');
                    const scoreInputs = questionItem.querySelectorAll('.option-score');
                    if (scoreSettingsContainer) {
                        scoreSettingsContainer.style.display = this.checked ? 'block' : 'none';
                    }
                    scoreInputs.forEach(input => {
                        input.style.display = this.checked ? 'flex' : 'none';
                    });
                }
            });
        });
    }
});


// 添加输入验证函数
function validateInput(input) {
    if (!input.value) return;

    let value = parseInt(input.value);
    
    // 处理填写次数的限制
    if (input.id === 'fillCount') {
        // 强制限制在1-1000范围内
        value = Math.max(1, Math.min(1000, value));
        input.value = value;
        
        // 立即触发信效度重新计算
        const enableReliability = document.getElementById('enableReliability');
        if (enableReliability && enableReliability.checked) {
            calculateReliability();
        }
    }
    // 如果是间隔时间，确保最小值不大于最大值
    else if (input.id === 'intervalMin' || input.id === 'intervalMax') {
        if (value < 1) {
            input.value = 1;
        }
        const min = parseInt(document.getElementById('intervalMin').value) || 1;
        const max = parseInt(document.getElementById('intervalMax').value) || 1;

        if (min > max) {
            if (input.id === 'intervalMin') {
                input.value = max;
            } else {
                document.getElementById('intervalMin').value = min;
            }
        }
    }
}



    /**
     * 信效度检验UI交互功能
     * 用于处理信效度检验相关的UI交互
     */

    document.addEventListener('DOMContentLoaded', function() {
        // 获取信效度检验相关元素
        const enableReliabilityCheckbox = document.getElementById('enableReliability');
        const reliabilitySettings = document.getElementById('reliabilitySettings');
        const reliabilityQuestionsContainer = document.getElementById('reliabilityQuestionsContainer');

        // 如果元素不存在，直接返回
        if (!enableReliabilityCheckbox || !reliabilitySettings) return;

        // 添加信效度检验复选框的事件监听器
        enableReliabilityCheckbox.addEventListener('change', function() {
            // 显示或隐藏信效度设置区域
            reliabilitySettings.style.display = this.checked ? 'block' : 'none';

            // 如果启用了信效度检验，并且已经解析了问卷，则加载题目并计算信效度
            if (this.checked && document.querySelectorAll('.question-item').length > 0) {
                loadReliabilityQuestions();
                calculateReliability();
            }
        });

        // 监听所有百分比滑块的变化
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('percentage-slider')) {
                // 如果启用了信效度检验，则在百分比变化时重新计算
                if (enableReliabilityCheckbox.checked) {
                    // 使用setTimeout延迟计算，避免在调整多个滑块时频繁计算
                    clearTimeout(window.reliabilityCalculationTimeout);
                    window.reliabilityCalculationTimeout = setTimeout(calculateReliability, 300);
                }
            }
        });

        // 监听填写次数变化
        const fillCountInput = document.getElementById('fillCount');
        if (fillCountInput) {
            fillCountInput.addEventListener('input', function() {
                if (enableReliabilityCheckbox.checked) {
                    clearTimeout(window.reliabilityCalculationTimeout);
                    window.reliabilityCalculationTimeout = setTimeout(calculateReliability, 300);
                }
            });
        }

        // 加载信效度计算的题目选择
        function loadReliabilityQuestions() {
            // 清空容器
            const reliabilityQuestionsContainer = document.getElementById('reliabilityQuestionsContainer');
            if (!reliabilityQuestionsContainer) {
                console.error('找不到信效度题目容器');
                return;
            }
            reliabilityQuestionsContainer.innerHTML = '';

            // 获取所有单选题
            const questions = [];
            document.querySelectorAll('.question-item').forEach((item, index) => {
                const typeText = item.querySelector('.question-type').textContent.trim();
                const title = item.querySelector('.question-title').textContent;
                if (typeText === '[单选题]') {
                    questions.push({ index: index + 1, title }); // 使用index + 1作为题号
                }
            });

            // 如果没有可用的题目
            if (questions.length === 0) {
                reliabilityQuestionsContainer.innerHTML = '<div class="empty-message">没有找到适合计算信效度的题目（仅支持单选题）</div>';
                return;
            }

            // 创建题目选择列表
            questions.forEach(question => {
                const questionCheckbox = document.createElement('div');
                questionCheckbox.className = 'reliability-question-item';
                questionCheckbox.innerHTML = `
                    <label>
                        <input type="checkbox" class="reliability-question-checkbox" 
                               data-question-index="${question.index - 1}" checked>
                        <span class="question-number">第${question.index}题：</span>
                        <span class="question-title">${question.title}</span>
                    </label>
                `;
                reliabilityQuestionsContainer.appendChild(questionCheckbox);

                // 添加复选框变更事件
                const checkbox = questionCheckbox.querySelector('input[type="checkbox"]');
                checkbox.addEventListener('change', calculateReliability);
            });

            // 添加CSS样式
            const style = document.createElement('style');
            style.textContent = `
                .reliability-question-item {
                    display: flex;
                    align-items: center;
                    padding: 10px;
                    border-bottom: 1px solid #f0f0f0;
                    transition: background-color 0.3s;
                }
                .reliability-question-item:hover {
                    background-color: #f8f9fa;
                }
                .reliability-question-item label {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    cursor: pointer;
                }
                .reliability-question-item .question-number {
                    color: #1890ff;
                    font-weight: 500;
                    margin-right: 8px;
                    min-width: 60px;
                }
                .reliability-question-item .question-title {
                    flex: 1;
                    color: #333;
                }
                .reliability-question-item input[type="checkbox"] {
                    margin-right: 12px;
                    width: 16px;
                    height: 16px;
                }
                .empty-message {
                    text-align: center;
                    padding: 20px;
                    color: #999;
                    font-style: italic;
                    background: #f8f9fa;
                    border-radius: 4px;
                    margin: 10px 0;
                }
            `;
            document.head.appendChild(style);
        }
    });

    // 计算信效度
    function calculateReliability() {
        console.log('开始计算信效度...');
        const enableReliability = document.getElementById('enableReliability');
        if (!enableReliability || !enableReliability.checked) {
            console.log('信效度计算未启用');
            return;
        }

        const fillCount = parseInt(document.getElementById('fillCount').value) || 100;
        console.log('填写次数:', fillCount);
        const selectedQuestions = [];

        // 获取选中的题目
        document.querySelectorAll('.reliability-question-checkbox:checked').forEach(checkbox => {
            const questionIndex = parseInt(checkbox.getAttribute('data-question-index'));
            // 确保题目是单选题
            const questionItem = document.querySelectorAll('.question-item')[questionIndex];
            const typeText = questionItem?.querySelector('.question-type')?.textContent.trim();
            if (typeText === '[单选题]') {
                selectedQuestions.push(questionIndex);
            }
        });

        console.log('选中的单选题索引:', selectedQuestions);

        // 如果没有选中的题目或题目数量不足，显示提示
        if (selectedQuestions.length < 2) {
            console.log('选中的单选题数量不足');
            document.getElementById('cronbachAlpha').textContent = '至少需要两个题目';
            document.getElementById('cronbachAlphaInterpretation').textContent = '';
            // 添加提示样式
            document.getElementById('cronbachAlpha').style.color = '#ff4d4f';
            return;
        } else {
            // 恢复正常样式
            document.getElementById('cronbachAlpha').style.color = '#1890ff';
        }

        // 获取选中题目的配置
        const questionConfigs = [];
        selectedQuestions.forEach(index => {
            const questionItem = document.querySelectorAll('.question-item')[index];
            if (!questionItem) {
                console.log('未找到题目项:', index);
                return;
            }

            const options = [];
            const sliders = questionItem.querySelectorAll('.percentage-slider');
            const scoreInputs = questionItem.querySelectorAll('.score-input');
            
            // 检查是否所有选项的百分比之和为100
            let totalPercentage = 0;
            sliders.forEach((slider, optionIndex) => {
                const percentage = parseInt(slider.value) || 0;
                const score = parseInt(scoreInputs[optionIndex]?.value) || (optionIndex + 1);
                totalPercentage += percentage;
                options.push({ 
                    percentage,
                    score
                });
            });

            console.log(`题目 ${index + 1} 的选项配置:`, options);

            // 如果总和不为100，跳过这个问题
            if (Math.abs(totalPercentage - 100) > 1) {
                console.warn(`题目 ${index + 1} 的选项百分比之和不为100%: ${totalPercentage}%`);
                return;
            }

            questionConfigs.push({ options });
        });

        console.log('最终的问题配置:', questionConfigs);

        // 如果有效题目数量小于2，显示提示
        if (questionConfigs.length < 2) {
            console.log('有效单选题数量不足');
            document.getElementById('cronbachAlpha').textContent = '至少需要两个题目';
            document.getElementById('cronbachAlphaInterpretation').textContent = '';
            // 添加提示样式
            document.getElementById('cronbachAlpha').style.color = '#ff4d4f';
            return;
        }

        // 生成模拟数据并计算Cronbach's α系数
        console.log('开始生成数据...');
        const data = window.ReliabilityCalculator.generateDeterministicDataFromPercentages(questionConfigs, fillCount);
        console.log('生成的数据:', data);
        
        console.log('开始计算Cronbach\'s α系数...');
        const cronbachAlpha = window.ReliabilityCalculator.calculateCronbachAlpha(data);
        console.log('计算得到的Cronbach\'s α系数:', cronbachAlpha);

        // 更新显示
        document.getElementById('cronbachAlpha').textContent = cronbachAlpha.toFixed(3);
        const interpretation = window.ReliabilityCalculator.getReliabilityInterpretation(cronbachAlpha);
        document.getElementById('cronbachAlphaInterpretation').textContent = `(${interpretation})`;
    }

    // 获取信效度解释
    function getReliabilityInterpretation(value) {
        if (value >= 0.9) return '(优秀)';
        if (value >= 0.8) return '(良好)';
        if (value >= 0.7) return '(可接受)';
        if (value >= 0.6) return '(勉强可接受)';
        return '(不可接受)';
    }
